<!--
 * @Author: lmh
 * @Date: 2021-09-04 12:53:47
 * @LastEditTime: 2021-09-04 14:03:19
 * @LastEditors: lmh
 * @Description: Tab选项卡显示效果基类开发
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        a {
            color: #95a5a6;
        }
        section {
            width: 200px;
            height: 100px;
            font-size: 36px;
            background-color: yellowgreen;
            margin: 5px;
        }
    </style>
</head>
<body>
    <main class="tab1">
        <nav>
            <a href="javascript:;">按钮一</a>
            <a href="javascript:;">按钮二</a>
        </nav>
        <section style="background-color: turquoise;">1</section>
        <section>2</section>
    </main>
    <main class="tab2">
        <nav>
            <a href="javascript:;">按钮一</a>
            <a href="javascript:;">按钮二</a>
        </nav>
        <section style="background-color: turquoise;">1</section>
        <section>2</section>
    </main>
</body>
<script>
    function extend(sub, sup) {
        sub.prototype = Object.create(sup.prototype)
        // sub.prototype.constructor = sub
        Object.defineProperty(sub.prototype, "constructor", {
            value: sub,
            enumerable: false
        })
    }
    function Animation() {}
    Animation.prototype.show = function() {
        this.style.display = 'block'
    }
    Animation.prototype.hide = function() {
        this.style.display = 'none'
    }
    Animation.prototype.background = function (color) {
        this.style.color = color
    }

    function Tab(el, callback) {
        this.tab = document.querySelector(el)
        this.links = this.tab.querySelectorAll('a')
        this.sections = this.tab.querySelectorAll('section')
        this.callback = callback
    }
    extend(Tab, Animation)
    Tab.prototype.run = function() {
        this.bindEvent()
        this.rest()
        this.action(0)
    }
    Tab.prototype.bindEvent = function() {
        this.links.forEach((el, i) => {
            el.addEventListener('click', () => {
                this.rest()
                this.action(i)
                if (this.callback) {
                    this.callback()
                }
            })
        });
    }
    Tab.prototype.action = function(i) {
        this.background.call(this.links[i], '#e67e22')
        this.show.call(this.sections[i])
    }
    Tab.prototype.rest = function() {
        this.links.forEach((el, i) => {
            this.background.apply(this.links[i], ['#95a5a6'])
            this.hide.apply(this.sections[i])
        })
    }
    new Tab('.tab2', function() {
        console.log('回调函数')
    }).run()
    new Tab('.tab1').run()
</script>
</html>
